<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="employeeName">
        <el-input
          v-model="queryParams.employeeName"
          placeholder="请输入姓名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编码" prop="employeeCode">
        <el-input
          v-model="queryParams.employeeCode"
          placeholder="请输入编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="查询码" prop="lookup">
        <el-input
          v-model="queryParams.lookup"
          placeholder="请输入查询码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idNumber">
        <el-input
          v-model="queryParams.idNumber"
          placeholder="请输入身份证号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门" prop="departmentId">
        <el-input
          v-model="queryParams.departmentId"
          placeholder="请输入部门"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="部门名称" prop="departmentName">
        <el-input
          v-model="queryParams.departmentName"
          placeholder="请输入部门名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="moblie">
        <el-input
          v-model="queryParams.moblie"
          placeholder="请输入手机号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input
          v-model="queryParams.email"
          placeholder="请输入邮箱"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信" prop="weiChat">
        <el-input
          v-model="queryParams.weiChat"
          placeholder="请输入微信"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="唯一识别码" prop="openId">
        <el-input
          v-model="queryParams.openId"
          placeholder="请输入唯一识别码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option label="请选择字典生成" value />
        </el-select>
      </el-form-item>
      <el-form-item label="图片" prop="pictureId">
        <el-input
          v-model="queryParams.pictureId"
          placeholder="请输入图片"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="删除标志" prop="deleted">
        <el-select v-model="queryParams.deleted" placeholder="请选择删除标志" clearable size="small">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="显示顺序" prop="displayOrder">
        <el-input
          v-model="queryParams.displayOrder"
          placeholder="请输入显示顺序"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['archive-honor:employee:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['archive-honor:employee:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['archive-honor:employee:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['archive-honor:employee:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="employeeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="员工id" align="center" prop="employeeId" />
      <el-table-column label="姓名" align="center" prop="employeeName" />
      <el-table-column label="编码" align="center" prop="employeeCode" />
      <el-table-column label="查询码" align="center" prop="lookup" />
      <el-table-column label="身份证号" align="center" prop="idNumber" />
      <el-table-column label="部门" align="center" prop="departmentId" />
      <el-table-column label="部门名称" align="center" prop="departmentName" />
      <el-table-column label="手机号" align="center" prop="moblie" />
      <el-table-column label="邮箱" align="center" prop="email" />
      <el-table-column label="微信" align="center" prop="weiChat" />
      <el-table-column label="唯一识别码" align="center" prop="openId" />
      <el-table-column label="状态" align="center" prop="status" />
      <el-table-column label="图片" align="center" prop="pictureId" />
      <el-table-column label="删除标志" align="center" prop="deleted">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.deleted" />
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="displayOrder" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['archive-honor:employee:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['archive-honor:employee:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改员工对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="姓名" prop="employeeName">
                <el-input v-model="form.employeeName" placeholder="请输入姓名" />
              </el-form-item>
              <el-form-item label="编码" prop="employeeCode">
                <el-input v-model="form.employeeCode" placeholder="请输入编码" />
              </el-form-item>
              <el-form-item label="查询码" prop="lookup">
                <el-input v-model="form.lookup" placeholder="请输入查询码" />
              </el-form-item>
              <el-form-item label="身份证号" prop="idNumber">
                <el-input v-model="form.idNumber" placeholder="请输入身份证号" />
              </el-form-item>
              <el-form-item label="部门" prop="departmentId">
                <!-- <el-input v-model="form.departmentId" placeholder="请输入部门" /> -->
                <treeselect
                  v-model="form.departmentId"
                  :options="departmentNodes"
                  :show-count="true"
                  :default-expand-level="1"
                  @select="changeDepartment"
                  placeholder="选择部门"
                />
                <!-- :normalizer="normalizer" -->
              </el-form-item>
              <!-- <el-form-item label="部门名称" prop="departmentName">
                <el-input v-model="form.departmentName" placeholder="请输入部门名称" />
              </el-form-item>-->
              <el-form-item label="手机号" prop="moblie">
                <el-input v-model="form.moblie" placeholder="请输入手机号" />
              </el-form-item>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="grid-content">
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="请输入邮箱" />
              </el-form-item>
              <!-- <el-form-item label="微信" prop="weiChat">
                <el-input v-model="form.weiChat" placeholder="请输入微信" />
              </el-form-item>-->
              <!-- <el-form-item label="唯一码" prop="openId">
                <el-input v-model="form.openId" placeholder="请输入唯一识别码" />
              </el-form-item>-->
              <el-form-item label="状态">
                <el-radio-group v-model="form.status">
                  <el-radio label="1">请选择字典生成</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="头像" prop="pictureId">
                <!-- <el-input v-model="form.pictureId" placeholder="请输入图片" /> -->
                <el-upload
                  class="avatar-uploader"
                  :action="uploadPictureUrl"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="avatarUrl" :src="avatarUrl" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
              <el-form-item label="删除标志">
                <el-radio-group v-model="form.deleted">
                  <el-radio
                    v-for="dict in dict.type.sys_normal_disable"
                    :key="dict.value"
                    :label="parseInt(dict.value)"
                  >{{ dict.label }}</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="显示顺序" prop="displayOrder">
                <el-input v-model="form.displayOrder" placeholder="请输入显示顺序" />
              </el-form-item>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth"
import { addPicture, getPicture } from "@/api/system/picture";
import { listEmployee, getEmployee, delEmployee, addEmployee, updateEmployee } from "@/api/archive-honor/employee";

import { treeselect } from "@/api/system/dept";

import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Employee",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  data () {
    return {
      pictureType: 21,
      avatarUrl: '',
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      departmentNodes: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 员工表格数据
      employeeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: null, employeeCode: null, lookup: null, idNumber: null, departmentId: null, departmentName: null, moblie: null, email: null, weiChat: null, openId: null, status: null, pictureId: null, deleted: null, displayOrder: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ], updateTime: [
          { required: true, message: "更新时间不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    uploadPictureUrl () {
      return this.pictureType
        ? (process.env.VUE_APP_BASE_API + "/common/upload/" + this.pictureType)
        : (process.env.VUE_APP_BASE_API + "/common/upload")
    }
  },
  created () {
    this.getList();
  },
  methods: {
    async handleAvatarSuccess (res, file) {
      this.avatarUrl = URL.createObjectURL(file.raw);


      if (res.code !== 200) {
        this.$message.error(res.msg)
        return;
      }

      const filename = res.picture.originalFilename
      if (!filename) {
        return
      }

      const postData = {
        mimeType: res.picture.mimeType,
        extension: res.picture.extension,
        originalFilename: res.picture.originalFilename,
        // seoFilename: null, 
        // altAttribute: null, 
        // titleAttribute: null, 
        virtualPath: res.picture.virtualPath,
        url: res.url,
        // size: 356013, 
        employeeId: this.form.employeeId ? this.form.employeeId : 0,
        // displayOrder: this.maxDisplayOrder + 1,
        pictureType: 21, // 21 为头像 
      }
      // console.log('上传头像后的信息：', postData)
      // 添加头像
      const result = await addPicture(postData)
      if (result.code === 200) {
        // this.$emit('pictureChange', result.msg)

        this.form.pictureId = result.picture.pictureId;
        console.log('上传的图片为：', result, result.picture.pictureId)
      }
    },
    beforeAvatarUpload (file) {
      // console.log('上传文件的格式：', file.type)
      const isJPG = file.type === 'image/jpeg'
        || file.type === 'image/png'
        || file.type === 'image/gif';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG, PNG, GIF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    /** 查询部门下拉树结构 */
    getDepartmentTree () {
      treeselect().then(response => {
        this.departmentNodes = response.data;
        // const menu = { menuId: 0, menuName: '主类目', children: [] };
        // menu.children = this.handleTree(response.data, "id");
        // this.departmentNodes.push(menu);
        // this.departmentNodes = this.handleTree(response.data, "id");
        // console.log(this.departmentNodes)

      });
    },
    /** 转换部门数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    changeDepartment (node, i) {
      // console.log(node, i)
      this.form.departmentName = node.label;
    },
    /** 查询员工列表 */
    getList () {
      this.loading = true;
      listEmployee(this.queryParams).then(response => {
        this.employeeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        employeeId: null, employeeName: null, employeeCode: null, lookup: null, idNumber: null, departmentId: null, departmentName: null, moblie: null, email: null, weiChat: null, openId: null, status: 0, pictureId: null, deleted: 0, displayOrder: null, createBy: null, createTime: null, updateBy: null, updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.employeeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.form.deleted = 0
      this.open = true;
      this.title = "添加员工";

      // 加载部门数据
      this.getDepartmentTree();
    },
    /** 修改按钮操作 */
    async handleUpdate (row) {
      this.reset();

      // 加载部门数据
      this.getDepartmentTree();

      const employeeId = row.employeeId || this.ids
      var { data } = await getEmployee(employeeId);
      this.form = data;

      this.open = true;
      this.title = "修改员工";
      // 这里头像url
      var { picture: data } = await getPicture(data.pictureId);
      this.avatarUrl = 'http://localhost:8080' + picture.virtualPath;
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.employeeId != null) {
            updateEmployee(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEmployee(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const employeeIds = row.employeeId || this.ids;
      this.$modal.confirm('是否确认删除员工编号为"' + employeeIds + '"的数据项？').then(function () {
        return delEmployee(employeeIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download('archive-honor/employee/export', {
        ...this.queryParams
      }, `employee_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 108px;
  height: 108px;
  line-height: 108px;
  text-align: center;
}
.avatar {
  width: 108px;
  height: 108px;
  display: block;
}
</style>